package 我的Java学习_算法基础.day_01;

public class 二进制交换奇偶数 {
    public static void main(String[] args) {
        int a =9;
        int b = swap(a);
        System.out.println("原数"+":"+Integer.toString(a,2));
        System.out.println("奇偶交换后"+":"+Integer.toString(b,2));
        System.out.println("==============================");

        int c = 0b01000000_00000000_00000000_00000000;
        int d = swap(c);
        System.out.println("原数"+":"+Integer.toString(c,2)+"="+c);
        System.out.println("奇偶交换后"+":"+Integer.toString(d,2)+"="+d);
    }
    private static int swap(int n){
        int ou = n&0xaaaaaaaa;  //和 1010 1010 1010 ……1010做按位与运算，保留偶数位
        int ji = n&0x55555555;  //和 0101 0101 0101 ……0101做按位与运算，保留奇数位
        System.out.println("保留偶数位:"+Integer.toString(ou,2));
        System.out.println("保留奇数位:"+Integer.toString(ji,2));
        return (ou>>1)^(ji<<1);
    }
}
